<template>
  <div class="container">
    <Icon size="0.55rem" :name="iconName" @click="changeType()" class="icon-left" />
    <div v-if="type" ref="msgInput" class="msg-input" contenteditable="true" @input="changeText">{{ message }}</div>
    <Button v-else  class="voice-input" size="small" @touchstart="handleVoice" @touchend="handleVoice" ref="voiceButton">
      {{ voiceMsg }}
    </Button>
    <Icon size="0.55rem" name='/src/assets/images/send.png' class="icon-right" @click="OnsendMsg" />
    <Popup v-model:show="isPressed" :overlay="false" style="opacity: 0.6;margin-top: 50%;" >
      <div style="padding-top:5px">
        <div style="border:1px solid #ccc;display:inline-block;vertical-align:bottom">
          <div style="height:100px;width:300px;" ref="recwave"></div>
        </div>
      </div>
    </Popup>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref,nextTick, watch } from 'vue';
import { Button, Icon, Popup, Toast } from 'vant';
import Recorder from 'recorder-core';
import 'recorder-core/src/engine/mp3';
import 'recorder-core/src/engine/mp3-engine';
import 'recorder-core/src/extensions/waveview';
import 'recorder-core/src/extensions/lib.fft.js'
const recwave = ref(null);
const voiceButton = ref(null);
const test =ref(true)
const emit = defineEmits(['sendMsg', 'sendVoice']);
const message = ref('');
const type = ref(true);
const msgInput = ref(null);
const iconName = ref('/src/assets/images/mike.png');
const isPressed = ref(false);
const voiceMsg = ref('长按说话');
const localUrl = ref('');
const showWave = ref(false)
var rc = null;
const voice = ref(null);
const recordTime = ref();
const receiveDuration = ref();
const touchEnd = ref()
const touchStart = ref()
const duration = ref(0);
let wave = null;
const OnsendMsg = () => {
  if(!message.value.trim()){
    Toast('消息不能为空');
    return;
  }
  emit('sendMsg', message.value);
  message.value = '';
};
const OnsendVoice = () => {
  const reader = new FileReader();
  reader.readAsDataURL(voice.value);
  reader.onloadend = () => {
    const base64data = reader.result.split(',')[1];
    emit('sendVoice', base64data, (duration.value / 1000).toFixed(1));
  };
  reader.onerror = (error) => {
    console.error('Error reading voice file:', error);
  };

};
const handleVoice = () => {
  if (isPressed.value) {
    touchEnd.value = new Date().getTime();
    duration.value = touchEnd.value - touchStart.value - 100;
    if (duration.value < 1000) {
      Toast('录音时间太短');
      rc.stop();
      isPressed.value = false;
      voiceMsg.value = '长按说话';
      return;
    }
    stopRecord();
  } else {
    startRecord();
    touchStart.value = new Date().getTime();
  }
};

const openRc = () => {
  rc = null;
  wave = null;
  localUrl.value = '';
  const newRc = Recorder({
    type: 'mp3', // 录音格式，可以换成wav等其他格式
    sampleRate: 16000, // 录音的采样率，越大细节越丰富越细腻
    bitRate: 16, // 录音的比特率，越大音质越好
    onProcess: (
      buffers,
      powerLevel,
      bufferSampleRate,
      newBufferIdx,
      asyncEnd
    ) => {
      //录音实时回调，大约1秒调用12次本回调
      //可实时绘制波形，实时上传（发送）数据
      wave.input(buffers[buffers.length - 1], powerLevel, bufferSampleRate);

    }
  });
  newRc.open(
    () => {
      rc = newRc;
    },
    (msg, isUserNotAllow) => {
      console.log((isUserNotAllow ? 'UserNotAllow，' : '') + '无法录音:' + msg);
      alert('无法录音:' + msg);
    }
  )
};
watch(() => isPressed.value, (value) => {
  const buttonElement = voiceButton.value.$el;
  if(value){
    buttonElement.style.backgroundColor = '#c2fea2';
  }
  else{
    buttonElement.style.backgroundColor = '#ffffff';
  }
});
const startRecord = () => {
  if (rc && Recorder.IsOpen()) {
    recordTime.value = null;
    localUrl.value = '';
    rc.start(); // 开始录音
    isPressed.value = true;
    voiceMsg.value = '松开发送';
    nextTick(()=>{
      if (recwave.value) {
        //创建音频可视化图形绘制对象
        wave = Recorder.WaveView({ elem: recwave.value });
      }
    })
  }
};

const stopRecord = () => {
  if (!(rc && Recorder.IsOpen())) {
    isPressed.value = false;
    voiceMsg.value = '长按说话';
      rc.close(); // 释放录音资源
    alert('录音器未打开');
    return;
  }
  rc.stop(
    (blob, duration) => {
      recordTime.value = duration;
      localUrl.value = (window.URL || webkitURL).createObjectURL(blob);
      isPressed.value = false
      voiceMsg.value = '长按说话';
      voice.value = blob;
      OnsendVoice();
    },
    (msg) => {
      console.log('录音失败:' + msg);
      isPressed.value = false;
      voiceMsg.value = '长按说话';
      rc.close(); // 释放录音资源
    }
  );
};



const changeType = () => {
  iconName.value = type.value ? '/src/assets/images/Chat.png' : '/src/assets/images/mike.png';
  if (type.value) {
    openRc();
  } else {
    rc.close();
    rc = null;
  }
  type.value = !type.value;
};

const changeText = (e) => {
  message.value = e.target.innerText;
};

// 注册keydown事件，估计是div不支持keydown事件
onMounted(() => {
  if (msgInput.value) {
    msgInput.value.addEventListener('keydown', handleKeydown);
  }
});
onUnmounted(() => {
  if (rc) {
    rc.close();
  }
});

const handleKeydown = (event) => {
  if (event.key === 'Enter') {
    event.preventDefault(); // 阻止默认的回车换行行为
    OnsendMsg();
  }
};
</script>

<style scoped>
.container {
  height: auto;
  /* 允许高度自动调整 */
  display: flex;
  align-items: center;
  /* 确保内容和按钮垂直居中 */
  border-top: 1px solid #ccc;
  /* 只显示上边框 */
  padding: 3px;
  background-color: #f9f8f8;
}

.voice-input {
  width: 80%;
  font-size: 14px;
  line-height: 23px;
  min-height: 30px;
  text-align: center;
  border: solid 1px #cbcbcb;
  background-color: #ffffff;
  border-radius: 5px;
  resize: none;
  letter-spacing: 1px;
}

.msg-input {
  width: 80%;
  font-size: 14px;
  line-height: 23px;
  min-height: 26px;
  max-height: 100px;
  padding-top: 4.5px;
  padding-left: 5px;
  border: solid 1px #cbcbcb;
  background-color: #ffffff;
  border-radius: 5px;
  resize: none;
}

.msg-input:empty::before {
  content: "输入消息...";
  color: #ffffff;
}

.msg-input:focus::before {
  content: none;
}

.icon-left,
.icon-right {
  color: #5b5a5a;
  margin: 0 3.8%;
  display: flex;
  align-items: center;
  /* 确保图标垂直居中 */
}
.dddd{
  color: #c2fea2;
}
</style>
